from django import forms
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from django.core.validators import RegexValidator
from utils.img_code import check_code
from io import BytesIO
import uuid
import datetime
from web import models
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSMSForm, LoginForm
from django.db.models import Q


def register(request):
    if request.method == "GET":
        # get 请求
        form = RegisterModelForm()
        return render(request, 'register.html', {"form": form})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 使用 save 方法会自动过滤数据库中不存在的字段
        instance = form.save()
        # 获取免费版交易策略
        price_policy_obj = models.PricePolicy.objects.filter(category=1,title="免费版").first()
        # 创建交易记录
        models.Transaction.objects.create(
            status=2,
            order=uuid.uuid4(),
            user=instance,
            price_policy=price_policy_obj,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now(),
        )
        # 若提交的手机格式无误，则将响应状态以及跳转的url发送到前端
        return JsonResponse({'status': True, 'data': '/login/', })
    # 若数据格式错误，将错误信息传到页面上
    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    # 实例化 SendSmsForm 并带上request参数
    form = SendSmsForm(request, data=request.GET)
    # print(request.GET.get('mobile_phone'))
    # print(request.GET.get('tpl'))
    # 只校验手机号
    if form.is_valid():
        # 若提交的手机格式无误，则将响应状态发送到前端
        return JsonResponse({'status': True})
    # 若用户提交的数据校验不通过，则向前端显示错误信息
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """短信登录"""
    if request.method == "GET":
        form = LoginSMSForm()
        return render(request, 'login_sms.html', {'form': form})
    form = LoginSMSForm(data=request.POST)
    if form.is_valid():
        mobile_phone = form.cleaned_data['mobile_phone']
        user_obj = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        return JsonResponse({'status': True, 'data': '/index/'})

    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    """用户/密码登录"""
    if request.method == "GET":
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user_obj = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()
        if user_obj:
            # 登录成功后，设置 session 时间为 两周
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('index')
        form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})

def logout(request):
    """退出登录"""
    # 清空session
    request.session.flush()
    return redirect("index")


def img_code(request):
    """生成验证码"""
    img_object, code = check_code()
    # 将验证码存进 session
    request.session['img_code'] = code
    # 设置session 有效时间为 60秒
    request.session.set_expiry(60)
    # 创建内存空间
    stream = BytesIO()
    img_object.save(stream, 'png')
    # 将生成的图片返回到前端
    return HttpResponse(stream.getvalue())
